package com.google.jessewilson.codesearch.intellij;

import com.google.inject.Inject;
import com.google.jessewilson.codesearch.util.SymbolExtractor;
import com.google.jessewilson.codesearch.util.Nullable;
import com.intellij.openapi.editor.Editor;

/**
 * Find a reasonable default search term when a search action is invoked.
 *
 * @author jessewilson
 */
class SearchTermFinder {

  private final SymbolExtractor symbolExtractor;
  private final Editor editor;

  @Inject
  public SearchTermFinder(@Nullable Editor editor, SymbolExtractor symbolExtractor) {
    this.editor = editor;
    this.symbolExtractor = symbolExtractor;
  }

  String getBestSearchTerm() {
    if (editor == null) {
      return null;
    }

    // if there's a selection, use that, unless it contains a newline.
    // if it does, then return "" and hope that the most recent search
    // term is more useful
    String selectedText = editor.getSelectionModel().getSelectedText();
    if (selectedText != null && selectedText.length() != 0) {
      if(selectedText.contains("\n")) {
        return "";
      } else {
        return selectedText;
      }
    }

    // otherwise search for the term around the cursor
    int caretOffset = editor.getCaretModel().getOffset();
    CharSequence charsSequence = editor.getDocument().getCharsSequence();
    return symbolExtractor.extract(charsSequence, caretOffset);
  }
}
